<script setup lang="ts">
  import axios from 'axios'
  import { computed, onMounted, ref } from 'vue'
  import { useVirtualList } from '@vueuse/core'

  type Item = {
    id: number
    name: string
  }

  // 所有的数据，比如这个数组存放了十万条数据
  const allListData = ref<Item[]>([])

  const itemHeight = ref(40) // 每一条（项）的高度，比如 40 像素
  const count = ref(10) // 一屏展示几条数据
  const startIndex = ref(0) // 开始位置的索引
  const endIndex = ref(10) // 结束位置的索引
  const topVal = ref(0) // 父元素滚动位置

  // 获取十万条数据
  const getData = async () => {
    const res = await axios.get('http://localhost:3007/large-data')
    allListData.value = res.data.data
  }
  getData()

  const { list, containerProps, wrapperProps } = useVirtualList(allListData, {
    itemHeight: itemHeight.value,
  })
</script>
<template>
  <h2>虚拟列表-VueUse实现</h2>
  <div v-bind="containerProps" class="viewport">
    <div v-bind="wrapperProps" class="list">
      <div v-for="item in list" :key="item.data.id" class="item">
        {{ item.data.name }}
      </div>
    </div>
  </div>

  <RecycleScroller
    class="viewport"
    :items="allListData"
    :item-size="itemHeight"
    key-field="id"
    v-slot="{ item }"
    item-class="item"
  >
    <div class="user">
      {{ item.name }}
    </div>
  </RecycleScroller>
</template>

<style scoped lang="scss">
  // 虚拟列表容器盒子
  .viewport {
    box-sizing: border-box;
    width: 240px;
    height: 400px;
    border: solid 1px #000000;
    // 开启滚动条
    overflow-y: auto;
    // 开启相对定位
    position: relative;
    .list {
      width: 100%;
      height: auto;
      // 搭配使用绝对定位
      position: absolute;
      top: 0;
      left: 0;
      .item {
        box-sizing: border-box;
        width: 100%;
        height: 40px;
        display: flex;
        justify-content: center;
        align-items: center;
        // 隔行变色
        &:nth-child(even) {
          background: #c7edcc;
        }
        &:nth-child(odd) {
          background: pink;
        }
      }
    }
  }
</style>
